package tagsinput

import (
	"github.com/templui/templui/internal/components/badge"
	"github.com/templui/templui/internal/components/input"
	"github.com/templui/templui/internal/utils"
)

type Props struct {
	ID          string
	Name        string
	Value       []string
	Form        string
	Placeholder string
	Class       string
	HasError    bool
	Attributes  templ.Attributes
	Disabled    bool
	Readonly    bool
}

templ TagsInput(props ...Props) {
	{{ var p Props }}
	if len(props) > 0 {
		{{ p = props[0] }}
	}
	<div
		id={ p.ID + "-container" }
		class={
			utils.TwMerge(
				// Base styles
				"flex items-center flex-wrap gap-2 p-2 rounded-md border border-input bg-transparent shadow-xs transition-[color,box-shadow] outline-none",
				// Dark mode background
				"dark:bg-input/30",
				// Focus styles
				"focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]",
				// Disabled styles
				utils.If(p.Disabled, "opacity-50 cursor-not-allowed"),
				// Width
				"w-full",
				// Error/Invalid styles
				utils.If(p.HasError, "border-destructive ring-destructive/20 dark:ring-destructive/40"),
				p.Class,
			),
		}
		data-tui-tagsinput
		data-tui-tagsinput-name={ p.Name }
		data-tui-tagsinput-form={ p.Form }
		{ p.Attributes... }
	>
		<div class="flex items-center flex-wrap gap-2" data-tui-tagsinput-container>
			for _, tag := range p.Value {
				@badge.Badge(badge.Props{
					Attributes: templ.Attributes{"data-tui-tagsinput-chip": ""},
				}) {
					<span>{ tag }</span>
					<button
						type="button"
						class="ml-1 text-current hover:text-destructive disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
						disabled?={ p.Disabled }
						data-tui-tagsinput-remove
					>
						<svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3 pointer-events-none" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
							<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"></path>
						</svg>
					</button>
				}
			}
		</div>
		@input.Input(input.Props{
			ID:          p.ID,
			Class:       "border-0 shadow-none focus-visible:ring-0 h-auto py-0 px-0 bg-transparent rounded-none min-h-0 disabled:opacity-100 dark:bg-transparent",
			Type:        input.TypeText,
			Placeholder: p.Placeholder,
			Disabled:    p.Disabled,
			Readonly:    p.Readonly,
			Attributes: utils.MergeAttributes(
				templ.Attributes{"data-tui-tagsinput-text-input": ""},
				p.Attributes,
			),
		})
		<div data-tui-tagsinput-hidden-inputs>
			for _, tag := range p.Value {
				<input type="hidden" name={ p.Name } value={ tag }/>
			}
		</div>
	</div>
}
